<template>
  <div class="app-container v-flex">
    <filter-form :form="listQuery" :data="filterData" @search="search" @deleta="deleteDatas" @addForm="addForm" @resizeTable="resizeTable" />
    <div ref="main" class="v-flex-elastic">
      <el-table
        v-if="height>0"
        ref="multipleTable"
        v-loading="listLoading"
        :data="tableData"
        :default-expand-all="true"
        row-key="id"
        :height="height"
        style="width: 100%"
        @selection-change="handleTagChange">
        <el-table-column
          align="center"
          type="selection"
          width="50" />
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="50" />
        <el-table-column
          v-if="tableColumnCheckLists[0].ispass"
          prop="moduleName"
          align="left"
          width="300"
          show-overflow-tooltip
          label="模块名称" />
        <el-table-column
          v-if="tableColumnCheckLists[1].ispass"
          prop="url"
          align="center"
          show-overflow-tooltip
          label="模块路径" />
        <el-table-column
          prop="orderNo"
          align="center"
          show-overflow-tooltip
          label="排序号" />
        <el-table-column
          prop="memo"
          align="center"
          show-overflow-tooltip
          label="备注" />
        <el-table-column
          prop="status"
          align="center"
          show-overflow-tooltip
          label="启动状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status===1">已启动</span>
            <span v-else>未启动</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="logo"
          align="center"
          show-overflow-tooltip
          label="模块图标">
          <template slot-scope="scope">
            <img style="max-width: 26px;" :src="getUrl(scope.row.logo)" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="createUser"
          align="center"
          show-overflow-tooltip
          label="编制人员" />
        <!-- <el-table-column
          prop="dtDec"
          align="center"
          show-overflow-tooltip
          label="编辑时间" />-->
        <el-table-column
          fixed="right"
          align="center"
          width="120"
          class-name="small-padding fixed-width">
          <template #header>
            操作
            <el-dropdown :hide-on-click="false">
              <i class="el-icon-s-operation columnSetIco" />
              <el-dropdown-menu slot="dropdown">
                <el-checkbox-group v-model="tableColumnCheck">
                  <el-dropdown-item v-for="(item,index) in checkList" :key="index"><el-checkbox :key="item" :label="item" />
                  </el-dropdown-item>
                </el-checkbox-group>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <template slot-scope="{row ,$index}">
            <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-view"
              @click="view(row)" />
            <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-edit"
              @click="updateForm(row,$index)" />
            <el-button
              class="el-icon-defined"
              size="mini"
              icon="el-icon-delete"
              @click="deleteData(row,$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div class="page-box">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="getList" />
    </div>-->
    <base-dialog
      class="dictionary-type-dialog"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @updateData="updateData">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        :disabled="dialog.disabled"
        label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="模块名称" prop="moduleName">
              <el-input v-model="temp.moduleName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="所属平台"
              prop="dtName">
              <el-select
                v-model="temp.platformId"
                @change="changeSite">
                <el-option
                  v-for="item in optionsDept"
                  :key="item.id"
                  :label="item.platformName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级模块" prop="pId">
              <select-tree
                ref="tree_box1"
                v-model="temp.pId"
                :options="deptTreeData"
                :props="defaultProps" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="菜单路径"
              prop="dtCode">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.url"
                disabled />
              <el-input v-else v-model="temp.url" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="文件路径"
              prop="modulePath">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.modulePath"
                disabled />
              <el-input v-else v-model="temp.modulePath" />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item
              label="模块图标"
              prop="logo">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.logo"
                disabled />
              <el-input v-else v-model="temp.logo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-upload
              class="avatar-uploader"
              action="/dfs/upload"
              accept="image/*"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload">
              <el-button>文件上传</el-button>
            </el-upload>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="排序号"
              prop="orderNo">
              <el-input
                v-if="dialogStatus == 'update'"
                v-model="temp.orderNo"
                disabled />
              <el-input v-else v-model="temp.orderNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用">
              <el-switch v-model="temp.status" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否审核设计">
              <el-switch v-model="temp.auditorFlag" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item
              label="备注"
              prop="memo">
              <el-input v-model="temp.memo" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <!-- <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false">
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="!disabled"
          type="primary"
          @click="dialogStatus==='create'?addData():updateData()">
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { upload } from '@/api/sysm'
import { platform, treeList } from '@/api/dsc/sysm'
import { getList, saveOrUpdate, deleteById } from '@/api/dsc/sysm/modular'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscType',
  mixins: [tableMixin],
  data() {
    return {
      height: 0, // table高度
      tableData: [], // 表格数据
      multipleSelection: [], // 选择行的复选框
      modalpd: false, // 上级模块
      deptTreeData: [],
      defaultProps: {
        parent: 'pId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'label', // 标签显示
        children: 'children' // 子级
      },
      optionsDept: [],
      modol: [],
      listQuery: {// 搜索条件
        keyName: '',
        page: 1,
        size: 20
      },
      filterData: {
        moduleName: {
          key: 'moduleName',
          type: 'input',
          title: '模块名称',
          placeholder: '请输入模块名称'
        },
        // platform: {
        //   key: 'platform',
        //   type: 'select',
        //   title: '所属平台',
        //   placeholder: '所有',
        //   options: [],
        //   props: {
        //     label: 'platformName',
        //     value: 'id'
        //   }
        // },
        // Hierarchy: {
        //   key: 'Hierarchy',
        //   type: 'selectTree',
        //   title: '上级模块',
        //   placeholder: '所有',
        //   options: [],
        //   props: {
        //     parent: 'pId', // 父级唯一标识
        //     value: 'id', // 唯一标识
        //     label: 'label', // 标签显示
        //     children: 'children' // 子级'
        //   }
        // },
        // subset: {
        //   key: 'subset',
        //   type: 'select',
        //   title: '包含子级',
        //   placeholder: '所有',
        //   options: [],
        //   props: {
        //     label: 'platformName',
        //     value: 'id'
        //   }
        // },
        status: {
          key: 'status',
          type: 'status',
          title: '是否启用',
          options: [
            {
              label: 1,
              value: '是'
            },
            {
              label: 0,
              value: '否'
            }
          ]
        }
      },
      platformOptions: [], // 所属平台option
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {// 弹窗表单
      //  id: null,
      //   dtName: '',
      //   dtCode: '',
      //   dtDec: '',
      //   isPub: true,
      //   isSystem: true,
      //   status: true,
      //   auditorFlag: true
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        // dtName: [{ required: true, message: '必填', trigger: 'blur' },
        //   { min: 1, message: '大于1个字符', trigger: 'blur' },
        //   { max: 20, message: '小于20个字符', trigger: 'blur' }],
        // dtCode: [{ required: true, message: '必填', trigger: 'blur' },
        //   { min: 1, message: '大于1个字符', trigger: 'blur' },
        //   { max: 20, message: '小于20个字符', trigger: 'blur' }],
        // dtDec: [{ max: 255, message: '小于255个字符', trigger: 'blur' }]
      },
      listLoading: false,
      disabled: false, // 是否禁止表单操作
      tableColumnCheck: ['模块名称', '模块路径'],
      checkList: ['模块名称', '模块路径'],
      tableColumnCheckLists: [
        { label: '模块名称', prop: 'moduleName', ispass: true },
        { label: '模块路径', prop: 'url', ispass: true }
      ]
    }
  },

  watch: {
    tableColumnCheck(newVal) {
      if (newVal) {
        var arr = this.checkList.filter(i => newVal.indexOf(i) < 0) // 未选中
        this.tableColumnCheckLists.map(i => {
          if (arr.indexOf(i.label) !== -1) {
            i.ispass = false
          } else {
            i.ispass = true
          }
        })
      }
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    this.getList()
    platform().then(response => {
      this.optionsDept = response.data
      this.filterData.platform.options = response.data
    }).catch(() => {
    })
  },
  methods: {
    getUrl(item) {
      return (
        process.env.VUE_APP_BASE_API +
        '/sysm/files/download?fileUrl=' +
        item
      )
    },
    // 图片上传
    beforeAvatarUpload(file) {
      const param = new FormData()
      param.append('file', file)
      upload(param).then(response => {
        this.temp.logo = response.data
      })
      return false
    },
    changeSite(data) {
      treeList({ platformId: data }).then(response => {
        this.deptTreeData = response.data.children
        this.filterData.Hierarchy.options = response.data.children
      }).catch(() => {
      })
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data
        setTimeout(() => {
          this.listLoading = false
        }, 0 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      this.changeSite(row.platformId)
      // this.disabled = true
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      // this.disabled = false
      this.changeSite(row.platformId)
      this.rowIndex = $index
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      const param = Object.assign({}, params)
      param.status = param.status ? 1 : 0
      param.auditorFlag = param.auditorFlag ? 1 : 0
      saveOrUpdate(param).then(response => {
        // response.data.status = !!response.data.status
        // response.data.auditorFlag = !!response.data.auditorFlag
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
        } else {
          // Object.assign(this.tableData[this.rowIndex], response.data)
        }
        this.getList()
        this.notifiySuccess('保存成功!')
        this.dialog.visible = false
      })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 启用、停用,是否系统
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?').then(() => {
        deleteById(row.id).then(response => {
          this.notifiySuccess('删除成功!')
          // this.tableData.splice($index, 1)
          // this.total--
          this.getList()
        })
      }).catch(() => {

      })
    },
    // 批量删除
    handleTagChange(val) {
      this.multipleSelection = val
    },
    deleteDatas() {
      const ids = []
      for (const i of this.multipleSelection) {
        // ids += ',' + i.id
        ids.push(i.id)
      }
      // ids = ids.substring(1)

      if (!ids) {
        Message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      let c = 0
      this.confirmBox('确定删除?').then(() => {
        ids.forEach(item => {
          deleteById(item).then(response => {
            c++
            if (ids.length === c) {
              this.notifiySuccess('删除成功!')
              this.getList()
            }
          })
        })
      }).catch(() => {

      })
    }
  }
}
</script>
